package com.ziq.zcamp.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

/**
 * 获取验证码倒计时TextView
 */
public class SMSCountDownTextView extends androidx.appcompat.widget.AppCompatTextView {

    private int mTimeCount;

    private CountDownTimer countDownTimer;

    public SMSCountDownTextView(Context context) {
        super(context);
        initView();
    }

    public SMSCountDownTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public SMSCountDownTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        setText("获取验证码");
    }

    /**
     *
     * @param timeCount
     */
    public void setTime(final int timeCount) {
        mTimeCount = timeCount;
        countDownTimer = new CountDownTimer(timeCount * 1000, 1000) {

            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
//                setTextColor(Color.parseColor("#ABABAB"));
                setText((millisUntilFinished / 1000) + "s");
            }

            @Override
            public void onFinish() {
                setEnabled(true);
                setClickable(true);
//                setTextColor(Color.parseColor("#6E5F55"));
                setText("重新获取");
            }
        };
    }

    public void startTimer() {
        if (countDownTimer != null) {
            setEnabled(false);
            setClickable(false);
            countDownTimer.start();
        }
    }

    public void cancelTimerCount() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
//            setTextColor(Color.parseColor("#6E5F55"));
            setText("获取验证码");
            setEnabled(true);
            setClickable(true);
            setTime(mTimeCount);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        super.onDetachedFromWindow();
    }
}
